﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using WorkWeChat.Domain;
using System.Xml;
using Tencent;
using Newtonsoft.Json;

namespace WorkWeChat
{
    public class SuiteTicketHelper
    {
        /// <summary>
        /// 从xml文档中提取suite_ticket
        /// </summary>
        public static string GetTicket(string xmlData)
        {
            string suite_ticket = string.Empty;
            XmlDocument xml = new XmlDocument();
            try
            {
                xml.LoadXml(xmlData);
                if (xml.GetElementsByTagName("SuiteTicket").Count > 0)
                    suite_ticket = xml.GetElementsByTagName("SuiteTicket")[0].InnerText;
            }
            catch (Exception ex) { }

            return suite_ticket;
        }

        public static Tuple<string, string> GetTicketInfo(string xmlData)
        {
            string SuiteId = string.Empty;      //第三方应用的SuiteId
            string suite_ticket = string.Empty;
            XmlDocument xml = new XmlDocument();
            try
            {
                xml.LoadXml(xmlData);
                if (xml.GetElementsByTagName("SuiteTicket").Count > 0)
                    suite_ticket = xml.GetElementsByTagName("SuiteTicket")[0].InnerText;

                if (xml.GetElementsByTagName("SuiteId").Count > 0)
                    SuiteId = xml.GetElementsByTagName("SuiteId")[0].InnerText;
            }
            catch (Exception ex) { }

            return Tuple.Create(SuiteId, suite_ticket);
        }

        /// <summary>
        /// 从xml文档中提取suite_ticket
        /// </summary>
        public static string GetInfoType(string xmlData)
        {
            string suite_ticket = string.Empty;
            XmlDocument xml = new XmlDocument();
            try
            {
                xml.LoadXml(xmlData);
                if (xml.GetElementsByTagName("InfoType").Count > 0)
                    suite_ticket = xml.GetElementsByTagName("InfoType")[0].InnerText;
            }
            catch (Exception ex) { Log("xml解析错误:" + ex.Message); }

            return suite_ticket;
        }

        /// <summary>
        /// 获取suite_ticket
        /// </summary>
        public static Suite_ticket GetTicket()
        {
            Suite_ticket tokenModel = new Suite_ticket();

            //suite_ticket 的存储目录
            string path = HttpContext.Current.Server.MapPath("~") + Config.suite_ticket_path;

            using (StreamReader sr = new StreamReader(path))
            {
                if (sr.Peek() > -1)
                    tokenModel.suite_access_token = sr.ReadLine();
                sr.Close();
            }
            return tokenModel;
        }

        /// <summary>
        /// 保存suite_ticket
        /// </summary>
        public static void SaveTicket(string suite_ticket)
        {
            if (string.IsNullOrEmpty(suite_ticket))
                return;
            //将suite_ticket 写入文件,方便程序读取
            string path = HttpContext.Current.Server.MapPath("~") + Config.suite_ticket_path;
            using (StreamWriter sw = new StreamWriter(path, false))
            {
                sw.WriteLine(suite_ticket);
                sw.WriteLine(DateTime.Now.ToString());
                sw.Close();
            }
        }


        public static string InstallCallback(string authCode)
        {
            //获取ticket
            Suite_ticket suite_ticket = SuiteTicketHelper.GetTicket();

            //获取套餐凭证
            Suite_Token suiteToken = WorkWeiXinSDK.Get_Suite_Token(suite_ticket.suite_access_token);

            //换取永久授权码以及授权信息
            PermanentCode permanentCode = WorkWeiXinSDK.Get_Permanent_Code(authCode, suiteToken);

            return JsonConvert.SerializeObject(permanentCode);
        }


        public static string Validate(string sVerifyMsgSig, string sVerifyTimeStamp, string sVerifyNonce, string sVerifyEchoStr)
        {
            string sEchoStr = "";
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(Config.Token, Config.EncodingAESKey, Config.CorpID);
            int ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr);
            if (ret != 0)
            {
                return "ERR: VerifyURL fail, ret: " + ret;
            }

            //ret==0表示验证成功，sEchoStr参数表示明文，用户需要将sEchoStr作为get请求的返回参数，返回给企业号。
            // HttpUtils.SetResponse(sEchoStr);

            return sEchoStr;
        }




        static void Log(string str)
        {
        }

    }
}